/**
 * 性能监控工具
 * 用于监控小程序性能，防止内存泄漏和卡死
 */

class PerformanceMonitor {
	constructor() {
		this.timers = new Map();
		this.websocketStatus = null;
		this.memoryUsage = null;
		this.isMonitoring = false;
		this.monitorInterval = null;
		this.warnings = []; // 新增警告列表
	}

	/**
	 * 开始性能监控
	 */
	startMonitoring() {
		if (this.isMonitoring) {
			return;
		}

		this.isMonitoring = true;


		// 每30秒检查一次性能状态
		this.monitorInterval = setInterval(() => {
			this.checkPerformance();
		}, 30000);
	}

	/**
	 * 停止性能监控
	 */
	stopMonitoring() {
		if (!this.isMonitoring) {
			return;
		}

		this.isMonitoring = false;
		if (this.monitorInterval) {
			clearInterval(this.monitorInterval);
			this.monitorInterval = null;
		}

	}

	/**
	 * 检查性能状态
	 */
	checkPerformance() {
		const report = {
			timestamp: Date.now(),
			timers: this.getTimerCount(),
			memory: this.getMemoryUsage(),
			websocket: this.checkWebSocketStatus(),
			warnings: this.warnings
		};
		
		// 清理过期的警告
		this.cleanupExpiredWarnings();
		
		// 如果警告过多，记录性能问题
		if (this.warnings.length > 10) {
			console.warn('检测到性能问题，警告数量:', this.warnings.length);
		}
		
		return report;
	}

	/**
	 * 检查内存使用情况
	 */
	checkMemoryUsage() {
		try {
			// 获取存储信息
			const storageInfo = uni.getStorageInfoSync();
			if (storageInfo) {
				const usageKB = storageInfo.currentSize || 0;
				const limitKB = storageInfo.limitSize || 10240; // 默认10MB
				const usagePercent = (usageKB / limitKB) * 100;

				if (usagePercent > 80) {
					console.warn(`存储使用率过高: ${usagePercent.toFixed(2)}%`);
				}

				this.memoryUsage = {
					current: usageKB,
					limit: limitKB,
					percent: usagePercent
				};
			}
		} catch (error) {
			console.error('检查内存使用失败:', error);
		}
	}

	/**
	 * 检查WebSocket状态
	 */
	checkWebSocketStatus() {
		try {
			const { getWSStatus } = require('./webSokent.js');
			const status = getWSStatus();
			
			// 检查连接状态
			if (!status.isConnected && !status.isConnecting) {
				console.warn('WebSocket未连接');
				this.addWarning('WebSocket未连接');
			}
			
			// 检查心跳状态
			if (status.lastHeartbeatTime > 0) {
				const timeSinceLastHeartbeat = Date.now() - status.lastHeartbeatTime;
				if (timeSinceLastHeartbeat > 60000) { // 超过1分钟没有心跳
					console.warn('WebSocket心跳超时');
					this.addWarning('WebSocket心跳超时');
				}
			}
			
			// 检查重连次数
			if (status.reconnectAttempts > 5) {
				console.warn('WebSocket重连次数过多');
				this.addWarning('WebSocket重连次数过多');
			}
			
			return status;
		} catch (error) {
			console.error('检查WebSocket状态失败:', error);
			return null;
		}
	}

	/**
	 * 注册定时器
	 * @param {string} id 定时器ID
	 * @param {number} timeout 超时时间
	 * @param {string} description 描述
	 */
	registerTimer(id, timeout, description = '') {
		this.timers.set(id, {
			timeout,
			description,
			startTime: Date.now(),
			expectedEndTime: Date.now() + timeout
		});
	}

	/**
	 * 注销定时器
	 * @param {string} id 定时器ID
	 */
	unregisterTimer(id) {
		this.timers.delete(id);
	}

	/**
	 * 清理过期的定时器
	 */
	cleanupExpiredTimers() {
		const now = Date.now();
		for (const [id, timer] of this.timers.entries()) {
			if (now > timer.expectedEndTime) {
				console.warn(`清理过期定时器: ${id} (${timer.description})`);
				this.timers.delete(id);
			}
		}
	}

	/**
	 * 获取性能报告
	 */
	getPerformanceReport() {
		return {
			timerCount: this.timers.size,
			memoryUsage: this.memoryUsage,
			websocketStatus: this.websocketStatus,
			isMonitoring: this.isMonitoring
		};
	}

	/**
	 * 强制清理所有资源
	 */
	forceCleanup() {

		
		// 清理定时器
		this.timers.clear();
		
		// 停止监控
		this.stopMonitoring();
		
		// 清理存储（可选）
		try {
			uni.clearStorageSync();
		} catch (error) {
			console.error('清理存储失败:', error);
		}
	}

	/**
	 * 添加警告
	 * @param {string} warning 警告信息
	 */
	addWarning(warning) {
		this.warnings.push({
			message: warning,
			timestamp: Date.now()
		});
		console.warn(warning);
	}

	/**
	 * 清理过期的警告
	 */
	cleanupExpiredWarnings() {
		const now = Date.now();
		this.warnings = this.warnings.filter(warning => now - warning.timestamp < 300000); // 保留最近5分钟内的警告
	}

	/**
	 * 获取定时器数量
	 */
	getTimerCount() {
		return this.timers.size;
	}

	/**
	 * 获取内存使用情况
	 */
	getMemoryUsage() {
		return this.memoryUsage;
	}
}

// 创建单例实例
const performanceMonitor = new PerformanceMonitor();

export default performanceMonitor; 